﻿//------------------------------------------------------------------------------
//  
//------------------------------------------------------------------------------
#region Imported Namespaces
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Text;
using SSRS;
using PHSRAG.Insight21.Reports;
using PHSRAG.Insight21.InsightUtilities;
using Utils = PHSRAG.Insight21.InsightUtilities;
using PHSRAG.Insight21.SearchContext;
using LaborDistributions = PHSRAG.Insight21.Personnel.LaborDistributions;
using MonthlyLaborDistributions = PHSRAG.Insight21.Personnel.MonthlyLaborDistributions;
using AgreementsConstants = PHSRAG.Insight21.InsightUtilities.Constants.AgreementsConstants;
using CommonSearchContext = PHSRAG.Insight21.SearchContext.CommonSearchContext;
using InsightConstants = PHSRAG.Insight21.InsightUtilities.Constants;

#endregion

namespace PHSRAG.Insight21.Personnel.Reports {
    
    public class sqlLaborDistributionReport : sqlReport
    {
        private bool isMonthly = false;
        private bool isGL = false;
        private const string mReportTitle = "Monthly Labor Distribution";
        private const string dReportTitle = "Labor Distribution";
        private const string glReportTitle = "Labor Distribution with GL";
        private const string CurrentDetailEndDateKey = "CurrentDetailEndMonth_21D58C0E-C5BA-4581-AB9A-45F097A67BD6";
        private const string SearchCriteriaVersionKey = "SearchCriteriaVersion_21D58C0E-C5BA-4581-AB9A-45F097A67BD6";
        public const char LabelValueSeparator = '|';

        public sqlLaborDistributionReport(string pageUrl)
            : base(pageUrl)
        {
            doCustomExcelReport = true;

            // test if monthly labor distribution report
            if (pageUrl.ToLower().Contains("month"))
            {
                isMonthly = true;
            }
            else if (pageUrl.ToLower().Contains("distributiongl"))
            {
                isGL = true;
            }
        }

        public override string ReportName
        {
            get
            {
                string rep;
                if (isMonthly)
                {
                    rep = "Agmt_MonthlyLaborDistribution";
                }
                else if (isGL)
                {
                    rep = "Agmt_LaborDistributionGL";
                }
                else
                {
                    rep = "Agmt_LaborDistribution";
                }
                return rep;
            }

        }

        public override ParameterValue[] setParameters(ref string rptName)
        {
            if (isMonthly)
            {
                reportTitle = mReportTitle;
            }
            else if (isGL)
            {
                reportTitle = glReportTitle;
            }
            else
            {
                reportTitle = dReportTitle;
            }
            rptName = ReportName;
            if (isMonthly)
            {
                MonthlyLaborDistributions monthlyLaborDistributions = MonthlyLaborDistributions;
                reportSource = monthlyLaborDistributions.GetDataContainer();
                reportResultCount = monthlyLaborDistributions.Count.ToString();
            }
            else
            {
                LaborDistributions laborDistributionsInstance = LaborDistributionsInstance;
                reportSource = laborDistributionsInstance.GetDataContainer();
            }
            reportCriteria = loadCriteria(searchCriteria);


            return base.setParameters(ref rptName);
        }

        private LaborDistributions LaborDistributionsInstance
        {
            get
            {
                LaborDistributions laborDistributions =
                   Policy.ResultsCache.GetObject(cachePolicy, LaborDistributions.CacheKey) as LaborDistributions;

                if (laborDistributions == null)
                {
                    //UserContext userContext = (UserContext)cachePolicy.GetCachedObject(UserContext.CacheKey);

                    laborDistributions = new LaborDistributions();
                    Hashtable dictionary = pageCachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;

                    if (dictionary == null ||
                         dictionary[InsightConstants.PageNameKey] == null ||
                        (string)dictionary[InsightConstants.PageNameKey] == string.Empty)
                    {
                        dictionary = (Hashtable)pageCachePolicy.GetCachedObject("LaborDistributionDetailsKey");
                    }

                    string fundNumber = string.Empty;
                    string selectedBudgetDetailFundNumber = dictionary[Keys.SelectedBudgetDetailFundNumberKey] as String;
                    if (selectedBudgetDetailFundNumber != null && selectedBudgetDetailFundNumber != string.Empty)
                    {
                        //we came in from the budget details page and a fund was selected so use that one
                        //remove from the dictionary, and recache the dictionary.
                        fundNumber = selectedBudgetDetailFundNumber;
                    }
                    else
                    {
                        fundNumber = (string)dictionary[Keys.FundNumberKey];
                        if (fundNumber == null)
                            fundNumber = (string)dictionary[InsightConstants.FundNumberKey];
                    }

                    laborDistributions.Load(Utility.DataAccess.ConnectionString, Session.SessionID
                       , ((CommonSearchContext)cachePolicy.GetCachedObject(CommonSearchContext.CacheKey)).GetSearchCriteria(Page.Request.Url.ToString())
                       , dictionary, fundNumber);

                    pageCachePolicy.UnCache(Keys.IncomingDataKey);

                    Policy.ResultsCache.SetObject(cachePolicy, LaborDistributions.CacheKey, laborDistributions);
                }

                return laborDistributions;
            }
        }

        /// Get the labor distribution informations that the logged-in user has access to. The list of distributions is
        /// is maintained by the LabourDistributions business object within its data container. This object is cached.
        /// The LaborDistributions instance is loaded based on from where the user is navigating to this page.
        /// Everytime the page is loaded for the firsttime the LaborDistributions instance will be reloaded.
        /// </summary>
        private MonthlyLaborDistributions MonthlyLaborDistributions
        {
            get
            {
                int searchVersion = searchCriteria.Version;

                //added default values for the search criteriea the first time the page is being loaded.
                if (searchCriteria["PayDateFrom"] == null)
                {
                    //Calculation of PayFromDate has been corrected as per TrackIt 7866    02/19/2008 jml29
                    searchCriteria["PayDateFrom"] = string.Format("10/1/{0}", ((DateTime.Now.Month > 9) ? 0 : -1) + DateTime.Now.Year);
                    searchCriteria["PayDateTo"] = DateTime.Now.ToString("MM/dd/yyyy");
                    searchContext.SetPrimarySearchCriteria(SearchCriteria.Level.Summary, Page.Request.Url.ToString(), "payDateFrom", string.Format("10/1/{0}", ((DateTime.Now.Month > 9) ? 0 : -1) + DateTime.Now.Year), "Pay Date From", LabelValueSeparator, string.Format("10/1/{0}", ((DateTime.Now.Month > 9) ? 0 : -1) + DateTime.Now.Year));
                    searchContext.SetPrimarySearchCriteria(SearchCriteria.Level.Summary, Page.Request.Url.ToString(), "payDateTo", DateTime.Now.ToString("MM/dd/yyyy"), "Pay Date To", LabelValueSeparator, DateTime.Now.ToString("MM/dd/yyyy"));
                }

                MonthlyLaborDistributions monthlyLaborDistributions =
                Policy.ResultsCache.GetObject(cachePolicy, MonthlyLaborDistributions.CacheKey) as MonthlyLaborDistributions;

                if ((monthlyLaborDistributions == null) || (searchVersion != SearchCriteriaVersion) ||
                    (monthlyLaborDistributions != null) && CurrentDetailEndDate.ToString("MM/dd/yyyy") != monthlyLaborDistributions.DetailEndDate.ToString("MM/dd/yyyy"))
                {

                    if (monthlyLaborDistributions != null)
                    {
                        Policy.ResultsCache.PurgeObject(cachePolicy);
                    }

                    monthlyLaborDistributions = new MonthlyLaborDistributions();
                    monthlyLaborDistributions.Search(searchCriteria, CurrentDetailEndDate.ToString("MM/dd/yyyy"));
                    
                    Policy.ResultsCache.SetObject(cachePolicy, MonthlyLaborDistributions.CacheKey, monthlyLaborDistributions);
                    SearchCriteriaVersion = searchVersion;
                }

                return monthlyLaborDistributions;
            }
        }

        /// <summary>
        /// Gets/sets an integer value indicating the search criteria version. 
        /// The version number changes when the search criteria changes.  This signals the page to re-build its
        /// cache.
        /// </summary>
        private int SearchCriteriaVersion
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.MonthlyLaborDistributionPageKey) as Hashtable;
                return (h == null || h[SearchCriteriaVersionKey] == null) ? 0 : (int)h[SearchCriteriaVersionKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.MonthlyLaborDistributionPageKey) as Hashtable;
                if (h == null)
                    h = new Hashtable();

                h[SearchCriteriaVersionKey] = value;
                pageCachePolicy.Cache(Keys.MonthlyLaborDistributionPageKey, h);
            }
        }

        /// <summary>
        /// Get/Set the current Detail end date within the datagrid for display. This information persists across page loads.
        /// This information is cached using the page cache policy
        /// Get: Return the value from the page cache policy, returns 0 if its not present in cache
        /// Set: Set the value and update the cache
        /// </summary>
        private DateTime CurrentDetailEndDate
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.MonthlyLaborDistributionPageKey) as Hashtable;
                return (h == null || h[CurrentDetailEndDateKey] == null) ? DateTime.Today : (DateTime)h[CurrentDetailEndDateKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(Keys.MonthlyLaborDistributionPageKey) as Hashtable;
                if (h == null)
                    h = new Hashtable();
                h[CurrentDetailEndDateKey] = value;
                pageCachePolicy.Cache(Keys.MonthlyLaborDistributionPageKey, h);
            }
        }

        protected override string loadCriteria(SearchCriteria searchCriteria)
        {
            StringBuilder criteria = new StringBuilder();
            if (isMonthly)
            {
                criteria.Append(searchCriteria.ToString(";"));
            }
             
            DateTime SalAsofDate = (DateTime)((DataSet)cachePolicy.GetCachedObject(RefreshDatesControlKey)).Tables[0].Rows[0]["salaryAsOfDate"];
            return criteria.AppendFormat(
                "{0}"
                , "Last Salary Post|" + SalAsofDate.ToShortDateString() + ";"
            ).ToString();
        }
  
    }
}
